package com.bobi.tfca.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Component
@Slf4j
public class MailUtil {


    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String defaultFrom;

    /**
     * 添加附件
     *
     * @param helper      复杂邮件处理
     * @param attachments 附件地址
     * @throws MessagingException
     */
    private void addAttachments(MimeMessageHelper helper, List<String> attachments) throws MessagingException {
        String rootpath = HtmltoPdfUtil.getRootPath();
        for (int i = 0; i < attachments.size(); i++) {
            String filepath = rootpath + attachments.get(i);
            System.out.println(filepath);
            FileSystemResource file = new FileSystemResource(new File(filepath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
        }
    }

    /**
     * 临时生成的pdf的二进制数据 完成附件的添加
     *
     * @param helper      复杂邮件的helper
     * @param inputStream 二进制数据
     * @throws MessagingException
     */
    private void addAttachments(MimeMessageHelper helper, byte[] inputStream, String fileName) throws MessagingException {
        helper.addAttachment(fileName, new ByteArrayResource(inputStream));
    }

    /**
     * 以二进制临时pdf文件作为附件发送邮件
     *
     * @param to          发送目标邮箱
     * @param subject     邮件主题
     * @param text        内容
     * @param inputStream 二进制数据
     */

    public void sendSimpleTextMailbyBit(String to, String subject, String text, byte[] inputStream, String fileName) {
        if (StringUtils.isEmpty(to) || StringUtils.isEmpty(subject) || StringUtils.isEmpty(text)) {
            log.error("邮件-> {} 无法继续执行，因为缺少基本的参数：邮件主题、收件人、邮件内容", subject);
            throw new RuntimeException("邮件无法继续发送，因为缺少必要的参数！");
        }
        //获取附件进行发送
        if (inputStream != null) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper;
            try {
                helper = new MimeMessageHelper(message, true);
                helper.setFrom(defaultFrom);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(text, false);
                //添加附件
                addAttachments(helper, inputStream, fileName);
                javaMailSender.send(message);
                log.info("发送邮件成功: 主题->{}", subject);
            } catch (MessagingException e) {
                e.printStackTrace();
                log.error("发送HTML邮件失败：发件人：{},收件人：{}主题：{}", defaultFrom, to, subject);
            }
        } else {
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(defaultFrom);
            msg.setTo(to);
            msg.setSubject(subject);
            msg.setText(text);
            javaMailSender.send(msg);
            log.info("发送邮件成功: 主题->{}", subject);
        }

    }


    /**
     * 发送简单仅文本邮件
     *
     * @param to          发送目标邮箱
     * @param subject     邮件主题
     * @param text        内容
     * @param attachments 附件列表
     */
    public void sendSimpleTextMail(String to, String subject, String text, List<String> attachments) {
        if (StringUtils.isEmpty(to) || StringUtils.isEmpty(to) || StringUtils.isEmpty(to)) {
            log.error("邮件-> {} 无法继续执行，因为缺少基本的参数：邮件主题、收件人、邮件内容", subject);
            throw new RuntimeException("邮件无法继续发送，因为缺少必要的参数！");
        }
        //获取附件进行发送
        if (attachments != null && attachments.size() > 0) {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper;
            try {
                helper = new MimeMessageHelper(message, true);
                helper.setFrom(defaultFrom);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(text, false);
                //添加附件
                addAttachments(helper, attachments);
                javaMailSender.send(message);
                log.info("发送邮件成功: 主题->{}", subject);
            } catch (MessagingException e) {
                e.printStackTrace();
                log.error("发送HTML邮件失败：发件人：{},收件人：{}主题：{}", defaultFrom, to, subject);
            }
        } else {
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setFrom(defaultFrom);
            msg.setTo(to);
            msg.setSubject(subject);
            msg.setText(text);
            javaMailSender.send(msg);
            log.info("发送邮件成功: 主题->{}", subject);
        }
    }

    /**
     * 发送html邮件
     *
     * @param to          目标地址
     * @param subject     主题
     * @param text        内容
     * @param attachments 附件列表
     * @throws MessagingException
     */
    public void sendSimpleHtmlMail(String to, String subject, String text, List<String> attachments) throws MessagingException {
        if (StringUtils.isEmpty(to) || StringUtils.isEmpty(to) || StringUtils.isEmpty(to)) {
            log.error("邮件-> {} 无法继续执行，因为缺少基本的参数：邮件主题、收件人、邮件内容", subject);
            throw new RuntimeException("模板邮件无法继续发送，因为缺少必要的参数！");
        }
        //创建复杂有限发送对象
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(defaultFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
            if (attachments != null && attachments.size() > 0) {
                addAttachments(helper, attachments);
            }
            javaMailSender.send(message);
            log.info("发送HTML邮件成功：发件人：{},收件人：{},主题：{}", defaultFrom, to, subject);
        } catch (MessagingException e) {
            e.printStackTrace();
            log.error("发送HTML邮件失败：发件人：{},收件人：{}主题：{}", defaultFrom, to, subject);
        }
    }
}
